<?php

namespace App\Http\Controllers;

use App\Models\Follows;
use App\Models\Records;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;

/**
 * 用户相关
 * Class CateController
 * @package App\Http\Controllers
 */
class UserController extends Controller{
    /**
     * 登录用户详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function user(){
        try {
            $user = auth()->guard('api')->user();
            return $this->returnJson(0,'',$user);
        } catch (\Exception $e) {
            return $this->returnJson(1, '网络超时，请刷新再试');
        }
    }

    /**
     * 用户关注列表
     * @return \Illuminate\Http\JsonResponse
     */
    public function follows(){
        try {
            $userid = auth()->guard('api')->id();
            $lists = Follows::where('userid',$userid)
                ->with(['cate' => function ($query) {
                    $query->select('id', 'name','avatar')->get();
                }])->get();
            return $this->returnJson(0,'',$lists);
        } catch (\Exception $e) {
            return $this->returnJson(1, '网络超时，请刷新再试');
        }
    }


    public function userFollows(){
        try {
            $userid = auth()->guard('api')->id();
            $lists = Follows::where('userid',$userid)
                ->with(['cate' => function ($query) {
                    $query->select('id', 'name','avatar')->get();
                }])->orderBy('created_at', 'DESC')->get();
            $new = [];
            foreach ($lists as $list){
                $new[$list->created_at->format('Y年m月d日')][] = $list;
            }
            return $this->returnJson(0,'',$new);
        } catch (\Exception $e) {
            return $this->returnJson(1, '网络超时，请刷新再试');
        }
    }


    public function history(){
        try {
            $userid = auth()->guard('api')->id();
            Log::info($userid);
            $day = Carbon::now()->subDays(30);//只显示最近30天的播放记录
            $lists = Records::where('userid',$userid)
                ->whereDate('created_at','>',$day)
                ->with(['video' => function ($query) {
                    $query->select('id', 'title','thumb')->get();
                }])->orderBy('created_at', 'DESC')->get();
            $new = [];
            foreach ($lists as $list){
                $new[$list->created_at->format('Y年m月d日')][] = $list;
            }
            return $this->returnJson(0,'',$new);
        } catch (\Exception $e) {
            return $this->returnJson(1, '网络超时，请刷新再试');
        }
    }


    public function update(){
        $data = request()->only('username','avatar');
        auth()->guard('api')->user()->update($data);
        return $this->returnJson(0,'',auth()->guard('api')->user());
    }
}
